// pages/hospital-list/hospital-list.js
const app = getApp();

Page({
  data: {
    hospitalList: [],
    searchForm: {
      name: '',
      services: '',
      address: ''
    }
  },

  onLoad() {
    this.loadHospitalList();
  },

  onNameInput(e) {
    this.setData({
      'searchForm.name': e.detail.value
    });
  },

  onServicesInput(e) {
    this.setData({
      'searchForm.services': e.detail.value
    });
  },

  onAddressInput(e) {
    this.setData({
      'searchForm.address': e.detail.value
    });
  },

  handleSearch() {
    this.loadHospitalList();
  },

  handleReset() {
    this.setData({
      searchForm: {
        name: '',
        services: '',
        address: ''
      }
    }, () => {
      this.loadHospitalList();
    });
  },

  loadHospitalList() {
    app.showLoading();
    const params = { page: 1, size: 100 };
    
    if (this.data.searchForm.name) {
      params.name = this.data.searchForm.name;
    }
    if (this.data.searchForm.services) {
      params.services = this.data.searchForm.services;
    }
    if (this.data.searchForm.address) {
      params.address = this.data.searchForm.address;
    }

    app.request({
      url: '/hospital/list',
      method: 'GET',
      data: params
    }).then(res => {
      if (res.success) {
        const hospitals = (res.data.records || []).map(item => ({
          ...item,
          image: this.getFirstImage(item.images)
        }));
        this.setData({ hospitalList: hospitals });
      }
    }).catch(err => {
      app.showToast('加载失败');
      console.error(err);
    }).finally(() => {
      app.hideLoading();
    });
  },

  getFirstImage(images) {
    if (!images) {
      return 'https://img1.baidu.com/it/u=2531584226,2194794184&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500';
    }
    const imageArray = images.split(',');
    return imageArray[0] || 'https://img1.baidu.com/it/u=2531584226,2194794184&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500';
  },

  viewDetail(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/hospital-detail/hospital-detail?id=${id}`
    });
  }
});


